package me.numark.fragments;

import com.google.gson.Gson;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import me.numark.R;
import me.numark.model.User;
import me.numark.net.AuthorizedJsonObjectRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;
import me.numark.view.CircleImageView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link PeopleRecommendFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PeopleRecommendFragment extends Fragment
        implements View.OnClickListener, AdapterView.OnItemClickListener {

    private RegisterListener mListener;

    private TextView rightButton;

    private ListView mListView;

    private RecommendAdapter mAdapter;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment PeopleRecommendFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static PeopleRecommendFragment newInstance() {
        PeopleRecommendFragment fragment = new PeopleRecommendFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public PeopleRecommendFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_people_recommend, container, false);
        TextView title = (TextView) view.findViewById(R.id.title);
        title.setText(R.string.recommend_people);
        view.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        rightButton = (TextView) view.findViewById(R.id.right_text);
        rightButton.setEnabled(true);
        rightButton.setOnClickListener(this);
        rightButton.setText(R.string.next_step);
        mListView = (ListView) view.findViewById(R.id.list);
        mAdapter = new RecommendAdapter();
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (RegisterListener) activity;
            getRecommendedPeople();
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        submitFollows();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }


    private class RecommendAdapter extends BaseAdapter implements View.OnClickListener {

        @Override
        public int getCount() {
            return mUserList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = getActivity().getLayoutInflater()
                        .inflate(R.layout.friend_list_item, parent, false);
            }
            CircleImageView avatar = (CircleImageView) view.findViewById(R.id.avatar);
            TextView name = (TextView) view.findViewById(R.id.name);
            TextView desc = (TextView) view.findViewById(R.id.desc);
            TextView fansCount = (TextView) view.findViewById(R.id.fans_count);
            TextView signature = (TextView) view.findViewById(R.id.signature);
            ImageView checkBox = (ImageView) view.findViewById(R.id.check_box);
            User user = mUserList.get(position);
            if (!TextUtils.isEmpty(user.pic)) {
                Picasso.with(getActivity()).load(user.pic).into(avatar);
            }
            name.setText(user.nick);
            signature.setText(user.des);
            desc.setText(user.getFromType());
            fansCount.setText(getString(R.string.fans_count) + user.fans);
            checkBox.setTag(user);
            checkBox.setOnClickListener(this);
            return view;
        }

        @Override
        public void onClick(View v) {
            User user = (User) v.getTag();
            v.setSelected(!v.isSelected());
            if (v.isSelected()) {
                mSelectedSet.add(user.uid);
            } else {
                mSelectedSet.remove(user.uid);
            }
        }
    }

    private Set<Integer> mSelectedSet = new LinkedHashSet<Integer>();

    private void getRecommendedPeople() {
        String uid = Settings.getUid();
        String url = String.format(NetworkConstants.REGISTER_FOLLOWS_URL, uid);
        AuthorizedJsonObjectRequest request = new AuthorizedJsonObjectRequest(
                Request.Method.GET, url,
                null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                LogUtils.d("getTopics, response is " + response);
                RecommendResponse resp = new Gson()
                        .fromJson(response.toString(), RecommendResponse.class);
                if (resp.ret) {
                    mListener.onSuccess(null);
                    mUserList.clear();
                    mUserList.addAll(Arrays.asList(resp.data));
                    mAdapter.notifyDataSetChanged();
                } else {
                    mListener.onFailure(
                            response.optString("msg", getString(R.string.get_recommends_failed)));
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mListener.onFailure(getString(R.string.get_recommends_failed));
            }
        });
        NetworkHelper.getInstance().getRequestQueue().add(request);
        NetworkHelper.getInstance().getRequestQueue().start();
        mListener.onShowProgress(getString(R.string.get_recommends));
    }

    private String getFollowUidString() {
        String delimiter = "|";
        StringBuilder sb = new StringBuilder();
        Iterator<?> iterator = mSelectedSet.iterator();
        if (iterator.hasNext()) {
            sb.append(iterator.next().toString());
        }
        while (iterator.hasNext()) {
            sb.append(delimiter);
            sb.append(iterator.next().toString());
        }
        return sb.toString();
    }

    public void submitFollows() {
        String uid = Settings.getUid();
        String url = String.format(NetworkConstants.REGISTER_FOLLOWS_URL, uid);
        Map<String, String> body = new LinkedHashMap<String, String>();
        body.put("f_uid", getFollowUidString());
        AuthorizedJsonObjectRequest request = new AuthorizedJsonObjectRequest(
                Request.Method.POST, url,
                body, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                LogUtils.d("submitFollows, response is " + response);
                if (response.optBoolean("ret")) {
                    mListener.onNext(PeopleRecommendFragment.this, null);
                } else {
                    mListener.onFailure(
                            response.optString("msg", getString(R.string.submit_follows_failed)));
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mListener.onFailure(getString(R.string.submit_follows_failed));
            }
        });
        NetworkHelper.getInstance().getRequestQueue().add(request);
        NetworkHelper.getInstance().getRequestQueue().start();
        mListener.onShowProgress(getString(R.string.submit_follows));
    }

    private class RecommendResponse {

        boolean ret;

        User[] data;
    }

    private List<User> mUserList = new ArrayList<User>();

}
